<template>
  <search-bar @search="onSearch"/>
  <div class="btns" style="display: flex;">
    <el-upload
      action="#"
      accept=".xls, .xlsx"
      :before-upload="uploadXlsxToJson"
    >
      <el-button size="small" type="warning">批量新增</el-button>
    </el-upload>
    <el-button size="small" type="primary" @click="$router.push('/itemAdd')">单个新增</el-button>
    <a href="javascript:;" @click="exportFile">下载excel模板</a>
  </div>
   <el-table :height="500"  :data="items2" style="width: 100%">
    <el-table-column prop="itemName" label="商品名" />
    <el-table-column prop="price" label="价格">
      <template #default="{row}">
        <el-tag>
          {{row.price}}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="desc" label="描述">
      <template #default="{row}">
        <el-tooltip
          class="box-item"
          effect="dark"
          placement="bottom"
        >
          <div>
            {{ row.desc.length > 15 ? row.desc.substring(0, 10)+'...' :  row.desc}}
          </div>
          <template #content>
            <div style="width:500px">
              {{ row.desc }}
            </div>
          </template>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="sale" label="销量">
      <template #default="{row}">
        <el-tag :color="row.sale > 500? 'red': 'green'">
          {{ row.sale }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="onsale" label="上下架">
      <template #default="{row}">
        <el-switch
          v-model="row.onsale"
          :active-value="1"
          :inactive-value="0"
          inline-prompt
          active-text="上架"
          inactive-text="下架"
          @change="switchItemSaleStatus(row.id, row.onsale)"
        />
      </template>
    </el-table-column>
    <el-table-column prop="thumb" label="商品封面">
      <template #default="{row}">
        <el-image
          style="width: 100px; height: 100px"
          :src="row.thumb"
          :zoom-rate="1.2"
          :preview-src-list="row.pics2"
          preview-teleported
          fit="cover"
        />
      </template>
    </el-table-column>
    <el-table-column prop="createAt" label="上架时间" />
    <el-table-column label="操作">
      <template #default="{row}">
        <el-button type="primary" @click="$router.push({
          path: '/itemUpdate',
          query: {
            id: row.id
          }
        })" size="small">编辑</el-button>
        <el-button type="danger" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    layout="prev, pager, next, jumper, sizes"
    background
    :total="total"
    v-model:page-size="pageSize"
    v-model:current-page="page"
  />

</template>

<script>
//import { fetchItems, updateItem } from '@/api/item'
//mport SearchBar from '@/components/SearchBar.vue'
import { utils, writeFileXLSX, read } from 'xlsx'
export default {
  name: 'ItemLists',
  data () {
    return {
      items: [],
      total: 0,
      searchParams: {},
      page: 1, // 当前页 那一页数据
      pageSize: 10 // 一页多少条
    }
  },
  watch: {
    // 分页
    page () {
      this.fetchItems()
    },
    pageSize () {
      this.fetchItems()
    }
  },
  methods: {
    // 修改商品上下架状态
    switchItemSaleStatus (id, onsale) {
      updateItem({
        id,
        onsale
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            onClose: () => {
              this.fetchItems()
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg
          })
        }
      })
    },
    
    uploadXlsxToJson (file) {
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      fd.onloadend = () => {
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        const items = data.map(item => {
          return {
            itemName: item.商品名,
            price: item.商品价格,
            desc: item.商品描述
          }
        })
        console.log(items)
        // 发送请求 将items 发送给批量新增商品接口
      }
      return false
    },
    // 导出excel模板
    exportFile () {
      const data = [
        {
          商品名: '商品1',
          商品价格: 18,
          商品描述: '这是描述'
        }
      ]
      const ws = utils.json_to_sheet(data)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '商品表.xlsx')
    },
    onSearch (searchParams) {
      this.searchParams = searchParams
      this.fetchItems()
    },
    // 商品列表
    fetchItems () {
      fetchItems({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 200) {
          this.items = res.data.data.lists
          this.total = res.data.data.total
        }
      })
    }
  },
  created () {
    this.fetchItems()
  },
  computed: {
    items2 () {
      const items = []
      this.items.forEach(item => {
        const _item = { ...item }
        const pics2 = []
        _item.pics.forEach(pic => {
          pics2.push(pic.url)
        })
        _item.pics2 = pics2
        items.push(_item)
      })
      return items
    }
  },
  components: {
    SearchBar
  }
}
</script>

<style lang="scss" scoped>

</style>
